<?php
/**
 * Created by PhpStorm.
 * User: 93195
 * Date: 2018/6/14
 * Time: 18:01
 */
class signIn
{
    public static function index($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $pointSchemeModel = M('module_point_scheme');
        $signInRewardModel = M('sign_in_reward');
        Session::switchCustomer($customerId);
        $userModel = M('user');
        $pointModel = D('Point', 'Logic');

        $signInRewardWhere['id'] = $id;
//        $signInRewardWhere['startTime'] = ['elt', date('Y-m-d', time())];
//        $signInRewardWhere['endTime'] = ['egt', date('Y-m-d', time())];
//        $signInRewardWhere['deleted'] = 0;
        $result = $signInRewardModel->where($signInRewardWhere)->find();
//        if (!$result) {
//            Output::instance()->object([
//                'code' => 1,
//                'msg' => '签到奖励未生效'
//            ]);
//            return;
//        }
        $pointScheme = $pointSchemeModel->where(['id' => $result['pointSchemeId']])->find();
        if (!$pointScheme) $pointScheme = $pointSchemeModel->where(['cid' => $customerId, 'default' => 1, 'deleted' => 0, 'status' => 1])->find();
        $data = self::getSignData($userId, $id, $pointScheme);
        $ifSignToday = self::ifSignToday($userId, $id);
        $fullName = $userModel->where(['id' => $userId])->getField('fullName');
        $totalPoint = $pointModel->getUserPoint($userId);
        $result['point'] = $data['point'] ? $data['point'] : 0;
        $result['fullName'] = $fullName;
        $result['totalPoint'] = $totalPoint ? $totalPoint : 0;
        $result['ifSignToday'] = $ifSignToday;
        $result['signNum'] = $ifSignToday ? $data['signNum'] : $data['signNum'] - 1;

        Output::instance()->module('signIn', 'index')->object($result);
    }

    /**签到
     * @param int $id 签到奖励id
     */
    public static function signInIndex($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $pointSchemeModel = M('module_point_scheme');
        $signInRewardModel = M('sign_in_reward');
        Session::switchCustomer($customerId);
        $pointModel = D('Point', 'Logic');

        /*添加签到记录*/
        $signInRewardWhere['id'] = $id;
        $signInRewardWhere['startTime'] = ['elt', date('Y-m-d', time())];
        $signInRewardWhere['endTime'] = ['egt', date('Y-m-d', time())];
        $signInRewardWhere['deleted'] = 0;
        $signInReward = $signInRewardModel->where($signInRewardWhere)->find();
        if (!$signInReward) {
            Output::instance()->object([
                'code' => 1,
                'msg' => '签到奖励未生效'
            ]);
            return;
        }
        $pointSchemeId = $signInReward['pointSchemeId'];

        if (empty($pointSchemeId)) {
            $scheme = $pointSchemeModel->where(['cid' => $customerId, 'default' => 1, 'deleted' => 0, 'status' => 1])->find();//获取默认方案
        } else {//积分方案id为空，获取默认积分方案
            $scheme = $pointSchemeModel->where(['id' => $pointSchemeId, 'deleted' => 0, 'status' => 1])->find();
        }
        $record = self::addSignRecord($userId, $id, $scheme);//调用内部添加签到记录的方法
        if ($record == 'signed') return;

        /*奖励积分*/
        if ($scheme && $record) {
            $schemeName = $scheme['name'];
            $schemeId = $scheme['id'];
            $point = $record['point'];
            $addPointRes = $pointModel->addPoint(
                $userId,
                $point,
                'signIn',
                $record['id'],
                '签到',
                $record['time'] . '签到',
                $schemeId,
                $schemeName
            );
        }

        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok'
        ]);
    }


    /************************************************以下是私有方法***************************************************/

    /**添加签到记录。
     * @param int $userId 用户id
     * @param int $signId 签到奖励id
     * @param int $isHavePointScheme 是否有积分奖励
     * @return mixed
     */
    private static function addSignRecord($userId, $signId, $pointScheme)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $signRecordModel = M('sign_record');
        Session::switchCustomer($customerId);

        $todaySign = self::ifSignToday($userId, $signId);
        if ($todaySign) {
            Output::instance()->object([
                'code' => 1,
                'msg' => '今天已经签过了'
            ]);
            return 'signed';
        }
        $data = self::getSignData($userId, $signId, $pointScheme);
        $data['cid'] = $customerId;
        $data['userId'] = $userId;
        $data['time'] = date('Y-m-d H:i:s', time());
        $data['signId'] = $signId;
        $recordId = $signRecordModel->add($data);
        $record = $signRecordModel->where(['id' => $recordId])->find();
        return $record;
    }

    /**更新签到记录（没用上）
     * @param int $id 签到记录id
     * @param int $point 奖励积分
     * @param int $index 额外奖励标记（其实就是距离上次额外奖励出发时的天数）
     * @return bool
     */
    private static function updateSignRecord($id, $point, $index)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $signRecordModel = M('sign_record');
        Session::switchCustomer($customerId);

        $data = [
            'point' => $point,
            'index' => $index
        ];

        $res = $signRecordModel->where(['id' => $id])->save($data);

        if (is_numeric($res)) {
            return true;
        } else {
            return false;
        }
    }

    /**获取当天签到的信息
     * @param $userId
     * @param $signId
     * @param array $pointScheme
     * @return array
     */
    private static function getSignData($userId, $signId, $pointScheme = [])
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $signRecordModel = M('sign_record');
        Session::switchCustomer($customerId);

        $yesterdayWhere['time'] = ['like', date('Y-m-d', strtotime('-1 day')) . '%'];
        $yesterdayWhere['userId'] = $userId;
        $yesterdayWhere['signId'] = $signId;
        $yesterdaySign = $signRecordModel->where($yesterdayWhere)->find(); //获取昨天的签到记录
        if ($pointScheme) {               //昨天有签到并且签到有积分奖励
            $arrProperties = json_decode($pointScheme['property'], true);
            foreach ($arrProperties as $arrProperty) {
                if ($arrProperty['type'] == PROPERTY_TYPE_SIGN_IN && $arrProperty['status'] == 1) {
                    $property = $arrProperty;  //选出签到奖励积分属性
                    break;
                } else {
                    continue;
                }
            }

            if (isset($property)) {
                $lastPoint = $yesterdaySign['point'];
                $point = $property['fixedPoint'];
                $stagedDay = $property['stagedDay'];
                $stagedPoint = $property['stagedPoint'];
                $maxPoint = $property['maxPoint'];
                if ($yesterdaySign) {
                    $signNum = $yesterdaySign['signNum'] + 1;       //连续签到天数加一
                    $index = $yesterdaySign['index'] + 1;           //额外奖励标记加一
                    if ($stagedDay && $stagedDay - $index == 0) {  //存在连续签到额外奖励并且今天是额外奖励日
                        $index = 0;
                        $point = $lastPoint + $stagedPoint;
                    } elseif ($stagedDay && $stagedDay - $index != 0) {  //存在连续签到额外奖励并且今天不是额外奖励日
                        $point = $lastPoint;
                    }
                } else {
                    $signNum = 1;
                    $index = 0;
                }
                if ($point > $maxPoint) $point = $maxPoint;  //奖励积分不得超过最大积分限制
            }
        } elseif ($yesterdaySign && !$pointScheme) {        //昨天有签到并且签到无积分奖励
            $signNum = $yesterdaySign['signNum'] + 1;       //连续签到天数加一
            $index = 0;
            $point = 0;
        } else {                                            //断签后第一次签到
            $signNum = 1;
            $index = 0;
            $point = 0;
        }
        return [
            'signNum' => $signNum, //连续签到天数
            'index' => $index,     //距离上次签到获得额外奖励天数
            'point' => $point      //本次签到获得积分数
        ];
    }

    /**获取今天是否已经签到
     * @param $userId
     * @param $signId
     * @return bool
     */
    private static function ifSignToday($userId, $signId)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $signRecordModel = M('sign_record');
        Session::switchCustomer($customerId);

        $todayWhere['time'] = ['like', date('Y-m-d', time()) . '%'];
        $todayWhere['userId'] = $userId;
        $todayWhere['signId'] = $signId;
        $todaySign = $signRecordModel->where($todayWhere)->find(); //获取今天的签到记录

        if ($todaySign) {
            return true;
        } else {
            return false;
        }
    }
}